import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/material.dart';
import 'package:uitest/routers/application.dart';
import 'package:uitest/routers/routes.dart';
//import 'package:uitest/navigator/LoadingDialog.dart';
import 'package:uitest/service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() {
    // TODO: implement createState
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  int _counter = 0;

  int page = 1;
  List<Map> hotGoodsList = [];
  GlobalKey<RefreshFooterState> _footerKey = GlobalKey<RefreshFooterState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:Text('首页'),
      ),
      body: FutureBuilder(
        future: getHomePageContent(context),
        builder: (context,snapshot) {
          if (snapshot.hasData) {
            var data = json.decode(snapshot.data.toString());
            List<Map> swiper = (data['data']['slides'] as List).cast();
            
            List<Map> navigatorList = (data['data']['category'] as List).cast();
            
            String advertesPicture = data['data']['advertesPicture']['PICTURE_ADDRESS'];
            
            String leaderImage = data['data']['shopInfo']['leaderImage'];
            String leaderPhone = data['data']['shopInfo']['leaderPhone'];

            List<Map> recommendList = (data['data']['recommend'] as List).cast();


            String floor1Title =data['data']['floor1Pic']['PICTURE_ADDRESS'];//楼层1的标题图片
            String floor2Title =data['data']['floor2Pic']['PICTURE_ADDRESS'];//楼层1的标题图片
            String floor3Title =data['data']['floor3Pic']['PICTURE_ADDRESS'];//楼层1的标题图片
            List<Map> floor1 = (data['data']['floor1'] as List).cast(); //楼层1商品和图片 
            List<Map> floor2 = (data['data']['floor2'] as List).cast(); //楼层1商品和图片 
            List<Map> floor3 = (data['data']['floor3'] as List).cast(); //楼层1商品和图片 
          

            return EasyRefresh(
              refreshFooter: ClassicsFooter(
                key: _footerKey,
                bgColor: Colors.white,
                textColor: Colors.pink,
                moreInfoColor: Colors.pink,
                showMore: true,
                noMoreText: '',
                moreInfo: '加载中',
                loadReadyText: '上拉加载汇总',
              ),
              child: ListView(
                children: <Widget>[
                  SwiperDiy(swiperDataList: swiper),  // 滚动广告业
                  TopNavigator(navigatorList:navigatorList), // 菜单
                  AdBanner(advertesPicture:advertesPicture), // 图片 banner
                  LeaderPhone(leaderImage: leaderImage,leaderPhone: leaderPhone), // 调起电话url
                  Recommend(recommendList: recommendList),
                  FloorTitle(picture_address: floor1Title,),
                  FloorContent(floorGoodsList: floor1),
                  FloorTitle(picture_address: floor2Title,),
                  FloorContent(floorGoodsList: floor2),
                  FloorTitle(picture_address: floor3Title,),
                  FloorContent(floorGoodsList: floor3),
                  _hotGoods(),
              ],
            ),
               loadMore: () async {
                print('开始加载更多......');  // 获取火爆专区数据
                var formData = {'page': page};
                await request('homePageBelowConten', formData: formData)
                    .then((val) {
                  var data = json.decode(val.toString());
                  List<Map> newGoodsList = (data['data'] as List).cast();
                  setState(() {
                    hotGoodsList.addAll(newGoodsList);
                    page++;
                  });
                });
              },
            );
          }else {
            return Center (
              child: Text('加载中·······'),
            );
          };
        },)
      );
    }

    Widget hotTitle = Container(
      margin: EdgeInsets.only(top: 10),
      alignment: Alignment.center,
      color: Colors.transparent,
      padding: EdgeInsets.all(5.0),
      child: Text('火爆专区'),
    );

    Widget _wrapList() {
     if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {
              Application.router.navigateTo(
                context, '${Routes.detailPage}?id=${val['goodsId']}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(
                  val['image'],
                  width: ScreenUtil().setWidth(370),
                ),
                Row(
                   children: <Widget>[
                    Text(
                      val['name'],
                      maxLines: 1,
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                    ),
                   ]
                ),
                Row(
                  children: <Widget>[
                    Text('￥${val['mallPrice']}'),
                    Text('￥${val['price']}',
                        style: TextStyle(
                            color: Colors.black26,
                            decoration: TextDecoration.lineThrough))
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('');
    }
   }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[hotTitle, _wrapList()],
      ),
    );
  }

}




// 滚动栏
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;
  const SwiperDiy({Key key, this.swiperDataList}) : super(key: key);
  
  @override
  Widget build(BuildContext context) { 
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    var swiper = Swiper(
        itemBuilder:(BuildContext context,int index){
          return Image.network("${swiperDataList[index]['image']}",fit: BoxFit.fill,);
        },
        itemCount: swiperDataList.length,
        pagination: new SwiperPagination(),
        autoplay: true,
        onTap: (index){
              Application.router.navigateTo(context,"/detail?id=${swiperDataList[index]['goodsId']}");
        },
      );
    return Container(
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: swiper
    );
  } 
}

 // 导航元素
class TopNavigator extends StatelessWidget {
  final List navigatorList;
  const TopNavigator({Key key, this.navigatorList}) : super(key: key);

  Widget _grdiItemUI(BuildContext context,item){
    return InkWell(
      onTap: () {
        print('点击了导航--${item['mallCategoryName']}');
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width:ScreenUtil().setWidth(95),
          ),
          Text(item['mallCategoryName']),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (this.navigatorList.length >10) {
      this.navigatorList.removeRange(10, this.navigatorList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(250),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(5.0),
        children: navigatorList.map((item){
              return  _grdiItemUI(context, item);
        }).toList(),
      ),
    );
  }
}

// 自定义广告banner 
class AdBanner extends StatelessWidget {
  final String advertesPicture;

  const AdBanner({Key key, this.advertesPicture}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return InkWell(
      onTap: (){
        print('点击了广告');
      },
      child: Image.network(advertesPicture),
    );
  }
}

// 店长电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderImage;
  final String leaderPhone;

  const LeaderPhone({Key key, this.leaderImage, this.leaderPhone}) : super(key: key);
  

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: InkWell(
        onTap: _launchUrl,
        child: Image.network(leaderImage),
      ),
    );
  }
  
  void _launchUrl() async {
    String url = 'tel:' + leaderPhone;
    if (await canLaunch(url)){
      await launch(url);
    }else {
      throw 'url不能进行访问，异常';
    }
  }
}

// 商品推荐区域
class Recommend extends StatelessWidget {
  final List recommendList;

  const Recommend({Key key, this.recommendList}) : super(key: key);

 @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      height: ScreenUtil().setHeight(380),
      margin:EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[
          _titleWidget(),
          _recommedList(),
        ],
      ),
    );
  }
  
  // 推荐商品标题
  Widget  _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5,color: Colors.black12),
        )
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  Widget _recommedList(){
    return Container(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context,index){
          return _item(index,context);
        },
      ),
    );
  }

  Widget _item(index,context) {
    return InkWell(
      onTap: (){
       Application.router.navigateTo(context, "/detail?id=${recommendList[index]['goodsId']}");
      },
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(width: 0.5,color: Colors.black12),
          )
        ),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text(

                '${recommendList[index]['goodsName']}',
                maxLines: 2,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 16,
                ),
              ),
            _subPrice(recommendList[index]['mallPrice'],recommendList[index]['price']),
          ],
        ),
      ),
    );
  }

  Widget _subPrice(mallPrice,price) {
    return Container(
      height: ScreenUtil().setHeight(40),
      child: ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: 1,
        itemBuilder: (context,index){
          return  Row(
            children: <Widget>[
              Text(
                '¥${mallPrice}',
                style: TextStyle(
                  color:Colors.red,
                  fontSize: 16,
                ),
              ),
              Text(
                '¥${price}',
                style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: Colors.grey,
                ),
              )
            ],
          );
        },
      ),
    );
  }
}

// 楼层标题组件
class FloorTitle extends StatelessWidget {
  final String picture_address;

  const FloorTitle({Key key, this.picture_address}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(picture_address),
    );
  }
}

class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  const FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(context),
          _otherGoods(context),
        ],
      ),
    );
  }

  Widget _firstRow(context) {
    return Row(
      children: <Widget>[
        _goodsItem(context,floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context,floorGoodsList[1]),
            _goodsItem(context,floorGoodsList[2]),
          ],
        )
      ],
    );
  }

  Widget _otherGoods(context) {
    return Row(
      children: <Widget>[
        _goodsItem(context,floorGoodsList[3]),
        _goodsItem(context,floorGoodsList[4]),
      ],
    );
  }

  Widget _goodsItem(BuildContext context,Map goods){
   
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: (){
          Application.router.navigateTo(context, '${Routes.detailPage}?id=${goods['goodsId']}');
        },
        child: Image.network(goods['image']),
      ),
    );
  }
  
}